package day20;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

/**
 * SplitFileDemo.java
 * @author wangbiao
 *         email:785497344@qq.com
 * @Description 切割一个文件，并合并一个文件
 * @since 1.0.0
 * @Date 2013-6-27下午8:49:09
 */
public class SplitFileDemo {

	public static void main(String[] args) {
		splitFile();
		merge();
	}
	
	//合并切割后的文件
	public static void merge() {
		List<FileInputStream> list = new ArrayList<FileInputStream>();
		//遍历所有文件，与读取流关联
		File file = new File("e:\\splitfile");
		if (file.exists()) {
			File[] files = file.listFiles();
			for (int i = 0,len = files.length; i < len; i++) {
				try {
					FileInputStream fis = new FileInputStream(files[i]);
					list.add(fis);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				
			}
		}
		
		//遍历集合
		final Iterator<FileInputStream> it = list.iterator();
		
		//构造一个Enumeration枚举的内部类
		Enumeration<FileInputStream> e = new Enumeration<FileInputStream>() {
			
			@Override
			public FileInputStream nextElement() {
				return it.next();
			}
			
			@Override
			public boolean hasMoreElements() {
				return it.hasNext();
			}
		};
		
		SequenceInputStream sis = new SequenceInputStream(e);
		int len = 0;
		byte[] b = new byte[1024 *4];
		FileOutputStream fos = null;
		File dir = new File("e:\\merge");
		if (!dir.exists()) {
			dir.mkdir();
		}
		try {
			fos = new FileOutputStream(new File(dir, "胡夏-一定有个你.mp3"));
			while ((len = sis.read(b)) != -1) {
				fos.write(b, 0, len);
				fos.flush();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (null != fos) {
					fos.close();
				}
				if (null != sis) {
					sis.close();
				}
			} catch (IOException exe) {
				exe.printStackTrace();
			}
		}
		
		
		
	}
	
	//切割文件。注意：切割文件存放的文件夹，之前应该存在
	public static void splitFile() {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("E:\\胡夏-一定有个你.mp3");
			int len = 0;
			//按1M大小分割文件
			byte[] b = new byte[1024 * 1024];
			//定义一个文件名计数器
			int var = 1;
			File dir = new File("e:\\splitfile");
			if (!dir.exists()) {
				dir.mkdir();
			}
			while ((len = fis.read(b)) != -1) {
				fos = new FileOutputStream(new File(dir, (var++)+".part"));
				fos.write(b, 0, len);
				fos.flush();
				fos.close();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != fis) {
					fis.close();
				}
				if (null != fos) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
